package services

import (
	"encoding/json"
	"fmt"
	"github.com/labstack/gommon/log"
	"law_case_api/dto"
	"law_case_api/models"
	"strings"
	"time"
)

type CaseService struct {
}

// CreateCaseInfo 创建案件信息
func (_case CaseService) CreateCaseInfo(wzjCaseInfo models.WzjCaseInfo, wzjCaseDetail models.WzjCaseDetail) (bool, error) {
	tx := db.Begin()
	yearCaseCount := 0
	if err := tx.Raw("SELECT COUNT(1) FROM  wzj_db.wzj_case_info WHERE FROM_UNIXTIME(create_date,'%Y') = DATE_FORMAT(NOW(),'%Y'); ").Find(&yearCaseCount).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	if time.Now().Year() == 2021 {
		yearCaseCount += 190
	}

	wzjCaseInfo.IsEnabled = 1 //默认启用
	wzjCaseInfo.CaseCode = fmt.Sprintf("%s%s", wzjCaseInfo.CaseCode, fmt.Sprintf("%06d", yearCaseCount+1))
	if err := tx.Create(&wzjCaseInfo).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	wzjCaseDetail.CaseId = wzjCaseInfo.Id
	if err := tx.Create(&wzjCaseDetail).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	tx.Commit()
	return true, nil
}

// UpdateCaseInfo 更新案件信息
func (_case CaseService) UpdateCaseInfo(wzjCaseInfo models.WzjCaseInfo, wzjCaseDetail models.WzjCaseDetail) (bool, error) {
	tx := db.Begin()
	if err := tx.Where("id = ?", wzjCaseInfo.Id).
		Select("contract_code,case_type,case_step,case_name,case_litigation_status,case_reason_id,case_reason,case_investigator,case_clue_id,case_clue,case_publish_date").
		Updates(&wzjCaseInfo).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	if err := tx.Where("id = ?", wzjCaseInfo.Id).
		Select("case_plaintiff_id,case_plaintiff_name,case_defendant_id,case_defendant_name,case_third_id,case_third_name,court_lawyer,handling_lawyer,assistant_lawyer,case_supplier,judgment_or_mediation_amount,civil_object,one_court,one_court_name,one_case_code,one_hold_court_date,one_judge_date,two_court,two_court_name,two_case_code,two_hold_court_date,two_judge_date,three_court,three_court_name,three_case_code,three_hold_court_date,three_judge_date").
		Updates(&wzjCaseDetail).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	tx.Commit()
	return true, nil
}

// GetCaseInfoById 根据合同id获取合同详情
func (_case CaseService) GetCaseInfoById(caseId int) (dto.CaseInfoReq, error) {
	caseInfoReq := dto.CaseInfoReq{}
	sql := `SELECT a.id,a.customer_id,a.customer_name,a.contract_code,a.law_id,a.is_self_build,a.create_date,a.case_category,
	a.create_user_id,a.case_code,a.case_type,a.case_step,a.case_name,a.case_litigation_status,a.case_reason_id,a.case_reason,
	a.case_investigator,a.case_clue_id,a.case_clue,a.case_created_date,a.case_publish_date,b.case_id,b.court_lawyer,
	b.handling_lawyer,b.assistant_lawyer,b.case_supplier,b.judgment_or_mediation_amount,b.civil_object,b.one_court,
	b.one_court_name,b.one_case_code,b.one_hold_court_date,b.one_judge_date,b.two_court,b.two_court_name,b.two_case_code,
	b.case_plaintiff_id,b.case_plaintiff_name,b.case_defendant_id,b.case_defendant_name,b.case_third_id,b.case_third_name,
	b.two_hold_court_date,b.two_judge_date,b.three_court,b.three_court_name,b.three_case_code,b.three_hold_court_date,b.three_judge_date 
	FROM wzj_db.wzj_case_info a
	LEFT JOIN wzj_db.wzj_case_detail b ON a.id = b.case_id
	WHERE a.is_enabled=1 and a.id = ? `
	if err := db.Raw(sql, caseId).Limit(1).Find(&caseInfoReq).Error; err != nil {
		log.Error("GetContractById--查询失败,失败原因：", err)
		return caseInfoReq, err
	}
	return caseInfoReq, nil
}

// GetCaseListByCondition 根据登录人信息获取合同列表
func (_case CaseService) GetCaseListByCondition(userId int, isLaw bool, caseListReq dto.CaseListReq) ([]dto.CaseInfoReq, int64, error) {
	var list []dto.CaseInfoReq
	tx := db.Table("wzj_db.wzj_case_info as a").
		Joins("INNER JOIN wzj_db.wzj_case_detail b ON a.id = b.case_id ").
		Joins("INNER JOIN wzj_db.wzj_customer_info c ON c.id = b.case_plaintiff_id")
	tx.Where(" a.is_enabled=1 and a.case_category=?", caseListReq.CaseCategory)
	if len(caseListReq.CaseName) > 0 {
		tx = tx.Where(" a.case_name like ? ", "%"+caseListReq.CaseName+"%")
	}
	if caseListReq.CaseStep > 0 {
		tx = tx.Where(" a.case_step=? ", caseListReq.CaseStep)
	}
	if len(caseListReq.CaseTime) == 2 {
		tx = tx.Where(" a.case_created_date between ? and ? ", caseListReq.CaseTime[0], caseListReq.CaseTime[1])
	}
	if len(caseListReq.CaseKeyword) > 0 {
		likeStr := "%" + caseListReq.CaseKeyword + "%"
		tx = tx.Where(" (a.case_code like ? or b.one_case_code like ? or b.two_case_code like ? or b.three_case_code like ? or a.customer_name like ? or a.case_name like ?) ", likeStr, likeStr, likeStr, likeStr, likeStr, likeStr)
	}
	if !isLaw {
		tx = tx.Where(" a.customer_id=? ", userId)
	} else {
		law := LawService{}
		_law := models.WzjLawInfo{
			Id: int64(userId),
		}
		wzjLawInfo, _ := law.GetLawByCondition(_law)
		if wzjLawInfo.LawRole == 2 || wzjLawInfo.LawRole == 3 {
			tx = tx.Where(" create_user_id=? ", userId)
		} else {
			tx = tx.Where(" is_self_build=0 ")
		}
	}
	dataCount := int64(0)
	if err := tx.Count(&dataCount).Order("a.create_date desc").
		Limit(int(caseListReq.PageSize)).Offset(int((caseListReq.PageIndex - 1) * caseListReq.PageSize)).
		Select("a.id,a.customer_id,a.customer_name,a.contract_code,a.law_id,a.is_self_build,a.create_date,a.case_category,a.create_user_id,a.case_code,a.case_type,a.case_step,a.case_name,a.case_litigation_status,a.case_reason_id,a.case_reason,a.case_investigator,a.case_clue_id,a.case_clue,a.case_created_date,a.case_publish_date,a.is_enabled,\n\tb.case_id,b.case_plaintiff_id,c.customer_name case_plaintiff_name,b.case_defendant_id,b.case_defendant_name,b.case_third_id,b.case_third_name,b.court_lawyer,b.handling_lawyer,b.assistant_lawyer,b.case_supplier,b.judgment_or_mediation_amount,b.civil_object,b.one_court,b.one_court_name,b.one_case_code,b.one_hold_court_date,b.one_judge_date,b.two_court,b.two_court_name,b.two_case_code,b.two_hold_court_date,b.two_judge_date,b.three_court,b.three_court_name,b.three_case_code,b.three_hold_court_date,b.three_judge_date").
		Find(&list).Error; err != nil {
		log.Error("GetCaseListByCreateUserId--查询失败,失败原因：", err)
		return list, dataCount, err
	}

	return list, dataCount, nil
}

// GetSelectValueListBySelectCode 根据类型查询下拉菜单信息
func (_case CaseService) GetSelectValueListBySelectCode(selectCode string) []dto.SelectVale {
	var list []dto.SelectVale
	if err := db.Raw("SELECT select_value 'value',select_label 'label' FROM wzj_db.wzj_case_menu WHERE select_code=?", selectCode).Limit(1).
		Find(&list).Error; err != nil {
		log.Error("GetSelectValueListBySelectCode--查询下拉菜单信息失败,失败原因：", err)
		return list
	}
	return list
}

// GetCaseCountByCondition 根据客户id获取案件数量
func (_case CaseService) GetCaseCountByCondition(customerIds []int64) map[int64]dto.ObjectCount {
	var objectCounts []dto.ObjectCount
	var objectCountMap = make(map[int64]dto.ObjectCount)
	customerIdsBytes, _ := json.Marshal(customerIds)
	sqlInStr := strings.Replace(strings.Replace(string(customerIdsBytes), "[", "", -1), "]", "", -1)
	sql := fmt.Sprintf(`SELECT COUNT(customer_id) object_count,customer_id object_id FROM wzj_db.wzj_case_info 
		WHERE customer_id in(%s) GROUP BY customer_id`, sqlInStr)
	if err := db.Raw(sql).Find(&objectCounts).Error; err != nil {
		log.Error("GetCaseCountByCondition--根据客户id获取案件数量信息失败,失败原因：", err)
		return objectCountMap
	}
	for _, v := range objectCounts {
		objectCountMap[v.ObjectId] = v
	}
	return objectCountMap
}

// GetNeedCountList 获取所有需要开庭的数据信息
func (_case CaseService) GetNeedCountList() []dto.DashboardCaseData {
	var list []dto.DashboardCaseData
	sql := `SELECT a.id,a.case_code,a.case_name,b.one_court,b.one_court_name,b.one_hold_court_date,b.two_court,b.two_court_name,b.two_hold_court_date,b.three_court,b.three_court_name,b.three_hold_court_date FROM wzj_db.wzj_case_info a
	INNER JOIN wzj_db.wzj_case_detail b ON a.id = b.case_id
	WHERE (
	(b.one_hold_court_date !='' AND b.one_hold_court_date >= NOW()) OR 
	(b.two_hold_court_date !='' AND b.two_hold_court_date >= NOW()) OR 
	(b.three_hold_court_date !='' AND b.three_hold_court_date >= NOW())
	)
	ORDER BY b.one_hold_court_date,b.two_hold_court_date,b.three_hold_court_date desc `
	if err := db.Raw(sql).Find(&list).Error; err != nil {
		log.Error("GetNeedCountList--获取所有需要开庭的数据信息失败,失败原因：", err)
		return list
	}
	return list
}

// 获取
func (_case CaseService) GetCaseStepEchartsData() []models.EChartValue {
	var list []models.EChartValue
	sql := `SELECT COUNT(case_step) 'value',
	CASE case_step
		WHEN 1 THEN '等待公证书' 
	WHEN 2 THEN '审核公证书' 
	WHEN 3 THEN '新案待分配' 
	WHEN 4 THEN '文书准备' 
	WHEN 5 THEN '等待立案' 
	WHEN 6 THEN '补充取证' 
	WHEN 10 THEN '提交立案' 
	WHEN 13 THEN '一审立案受理' 
	WHEN 14 THEN '一审补充证据' 
	WHEN 15 THEN '一审准备开庭' 
	WHEN 16 THEN '一审再次开庭' 
	WHEN 17 THEN '一审庭后待判' 
	WHEN 20 THEN '一审等待上诉' 
	WHEN 21 THEN '一审待执行' 
	WHEN 22 THEN '一审上诉准备' 
	WHEN 23 THEN '一审补充代理意见' 
	WHEN 24 THEN '一审和解中' 
	WHEN 25 THEN '一审和解结案' 
	WHEN 26 THEN '二审立案受理' 
	WHEN 27 THEN '二审补充证据' 
	WHEN 28 THEN '二审通知开庭' 
	WHEN 31 THEN '二审再次开庭' 
	WHEN 32 THEN '二审庭后待判' 
	WHEN 33 THEN '二审待执行' 
	WHEN 38 THEN '二审补充代理意见' 
	WHEN 39 THEN '二审和解中' 
	WHEN 41 THEN '二审和解结案' 
	WHEN 42 THEN '再审立案受理' 
	WHEN 44 THEN '再审补充证据' 
	WHEN 45 THEN '再审通知开庭' 
	WHEN 46 THEN '再审庭后待判' 
	WHEN 47 THEN '再审待执行' 
	WHEN 48 THEN '再审和解中' 
	WHEN 49 THEN '再审和解结案' 
	WHEN 50 THEN '执行立案' 
	WHEN 51 THEN '执行受理' 
	WHEN 52 THEN '执行中止' 
	WHEN 53 THEN '执行结案' 
	WHEN 99 THEN '执行终本' 
	WHEN 100 THEN '案件作废'
		ELSE
			''
	END AS  'name' FROM wzj_db.wzj_case_info GROUP BY case_step;`
	if err := db.Raw(sql).Find(&list).Error; err != nil {
		log.Error("GetNeedCountList--获取所有需要开庭的数据信息失败,失败原因：", err)
		return list
	}
	return list
}
